package Calculator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class CalcClient {
    private String serverIp;
    private int serverPort;
    private DatagramSocket socket = null;

    public CalcClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while (true) {
            // 1. 用户输入的请求
            System.out.print("请输入操作数1: ");
            int num1 = sc.nextInt();
            System.out.print("请输入操作数2: ");
            int num2 = sc.nextInt();
            System.out.print("请输入运算符: ");
            String operator = sc.next();
            String request = num1+";"+num2+";"+operator;
            // 2. 构造请求,并发给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            // 3. 从服务器中读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            // 4. 将结果显示到屏幕上
            String log = String.format("req: %s; resp: %s",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        CalcClient client = new CalcClient("127.0.0.1",9090);
        client.start();
    }
}
